<?php
namespace  zhtfrontend\components\services\goods;

use common\components\helpers\Fun;
use zhtfrontend\models\datas\Goods;
use yii\base\Action;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use yii\widgets\ActiveForm;
use yii\web\Response;
use doumiaoduo\buildform\BuildForm;

class SetDepositAction extends Action{

    public $type;

    public function run(){
        $this->controller->layout=false;
        $goods_id = \Yii::$app->request->get('id');
        if ($goods_id == null) {
            throw new BadRequestHttpException(\Yii::t('frontend', '错误请求'));
        }
        $type = !empty(\Yii::$app->request->get('type_id')) ? \Yii::$app->request->get('type_id'):1;
        $this->type = $type;
        $modelgoods = Goods::findOne($goods_id);
        $modelgoods->scenario = 'setdeposit';
        if ($modelgoods ==null) {
            throw new NotFoundHttpException(\Yii::t('frontend', '信息不存在'));
        }

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $modelgoods->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($modelgoods);
        }
        $form = new BuildForm('@app/components/forms/goodsdepositForm.php');//直接使用组合商品的form，所以命名没更改
        $form->loadModel(['goods' => $modelgoods]);
        $form->loadDefaultValues();
        if ($form->loadData(\Yii::$app->request->post())&& $form->validate()) {
            if($modelgoods->save(false)) {
                $url = Fun::url([$this->controller->id . '/index', 'type_id' => $this->type]);
                if ($this->controller->id == 'goodsskill') {
                    $url = Fun::url([$this->controller->id . '/setlist']);
                }
//                return $this->controller->redirectMessage('修改成功',$url);
                return $this->controller->redirectMessage(\Yii::t('zhtfrontend', '设置成功'), $url);
            }

        }
        return $this->controller->render('@zhtfrontend/components/services/goods/deposit.php',['form' => $form->render()]);
    }

}